package com.beesoft.demo.service;

import com.beesoft.demo.dto.PageResponse;
import com.beesoft.demo.entity.Language;
import com.beesoft.demo.repository.LanguageRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class LanguageService {

    private final LanguageRepository languageRepository;

    public PageResponse<Language> searchLanguages(
            String search,
            String orderColumn,
            String orderDirection,
            int page,
            int perPage) {

        // 验证和处理排序参数
        Sort sort = createSort(orderColumn, orderDirection);

        // 创建分页对象（Spring Data 的页码从0开始）
        Pageable pageable = PageRequest.of(page - 1, perPage, sort);

        // 执行查询
        Page<Language> resultPage;
        if (search != null && !search.trim().isEmpty()) {
            // 搜索：在 code 和 title 字段中查找
            resultPage = languageRepository.findByCodeContainingIgnoreCaseOrTitleContainingIgnoreCase(
                    search, search, pageable);
        } else {
            // 无搜索条件，返回所有数据
            resultPage = languageRepository.findAll(pageable);
        }

        // 构建响应
        return PageResponse.of(
                resultPage.getContent(),
                resultPage.getTotalElements(),
                page,
                perPage
        );
    }

    private Sort createSort(String orderColumn, String orderDirection) {
        // 默认排序
        if (orderColumn == null || orderColumn.trim().isEmpty()) {
            orderColumn = "id";
        }

        // 验证排序字段（防止SQL注入）
        String[] allowedColumns = {"id", "code", "createdAt", "updatedAt"};
        boolean isValidColumn = false;
        for (String col : allowedColumns) {
            if (col.equalsIgnoreCase(orderColumn)) {
                orderColumn = col;
                isValidColumn = true;
                break;
            }
        }
        if (!isValidColumn) {
            orderColumn = "id";
        }

        // 验证排序方向
        Sort.Direction direction = Sort.Direction.ASC;
        if ("desc".equalsIgnoreCase(orderDirection)) {
            direction = Sort.Direction.DESC;
        }

        return Sort.by(direction, orderColumn);
    }
}

